package com.hd.vue2204.fm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hd.vue2204.fm.entity.User;
import com.hd.vue2204.fm.mapper.UserMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hd.vue2204.fm.service.UserService;
import com.hd.vue2204.fm.utils.Constants;
import com.hd.vue2204.fm.utils.SaltUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

/**
 * <p>
 * 用户  服务实现类
 * </p>
 *
 * @author hd
 * @since 2023-04-19
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    @Resource
    UserMapper userMapper;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean regist(String username, String password) {
        //1.查询当前用户名在数据库中是否存在，如果存在就抛异常
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        User dbuser = this.getOne(wrapper);
        if (dbuser != null){
            throw new RuntimeException("用户名已存在，注册失败");
        }else {
            //2.处理密码
            //2.1生成随机盐
            String salt = SaltUtils.getSalt(Constants.SALT_LENTH);
            String md5password = new Md5Hash(password, salt, Constants.HASH_TINES).toHex();

            //3.入库
            Date date = new Date(System.currentTimeMillis());
            User user = new User();
            user.setUsername(username);
            user.setPassword(md5password);
            user.setSalt(salt);
            user.setUserRegtime(date);
            user.setUserModtime(date);
            user.setSalt(salt);
            this.save(user);
            return true;
        }

    }
}
